use tokio::{
    sync::watch,
    time::{self, Duration},
};

use tracing::info;
use tracing_subscriber::EnvFilter;

use bc_p2p::BcP2PNetwork;

#[tokio::main]
async fn main() {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env())
        .try_init();

    info!("Starting libp2p file sharing example.");

    // Create a watch channel for shutdown signal.
    // Initially, false means "keep running". When set to true, tasks should shut down.
    let (shutdown_tx, shutdown_rx) = watch::channel(false);

    let (mut network, _event_receiver_for_app) =
        BcP2PNetwork::new_and_start(None, None, shutdown_rx)
            .await
            .unwrap();
    info!("BC P2P Network created and started.");

    // listen termial input command
    time::sleep(Duration::from_millis(100)).await;

    let input_listener = bc_p2p::crate_input_listener_for_p2p();

    tokio::select! {
        _ = input_listener => {
            println!("User entered 'exit'. Shutting down...");
            let _ = shutdown_tx.send(true);
        },

        _ = tokio::signal::ctrl_c() => {
            println!("Received Ctrl+C signal, stopping P2P network of blockchain ...");
            let _ = shutdown_tx.send(true);
        },
    }

    network.shutdown().await;

    println!("P2P network of blockchain application stopped");
}

// use bc_p2p::network_api::P2PEventForApp;
// pub async fn user_event_loop_task(
//     network_handler: &mut P2pNetWorkHandlerForApp,
//     mut event_receiver_for_app: tokio::sync::mpsc::Receiver<P2PEventForApp>,

//     content_id: ProvidingContentId,
//     mut shutdown_signal: tokio::sync::watch::Receiver<bool>,
// ) {
//     println!("🚀 Starting the event loop task for APP...");
//     bc_util::print_task_and_thread_id("P2P network user event task");
//     loop {
//         tokio::select! {
//             _ = shutdown_signal.changed() => {
//                 if *shutdown_signal.borrow() {
//                     info!("Shutdown signal received for the event for APP loop task.");
//                     break;
//                 }
//             },
//             event = event_receiver_for_app.recv() => {
//                 match event {
//                     // Reply with the content of the file on incoming requests.
//                     Some(P2PEventForApp::InboundRequest { request, channel }) => {
//                         if request == content_id {
//                             // TODO: Get the content ....
//                             let content = vec![];
//                             network_handler.respond_file_content(content, channel).await;
//                         }
//                     }
//                     e => todo!("{:?}", e),
//                 }
//             }
//         }
//     }
//     println!("🛑 The event loop task for APP stoped.");
// }
